package cn.sciento.boot.data.change.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SqlExecuteUtil {
  private static final Logger logger = LoggerFactory.getLogger(SqlExecuteUtil.class);
  
  public static List<Map<String, Object>> executeSql(Connection connection, String sql, Collection<Object> params) throws SQLException {
    List<Map<String, Object>> mapList;
    PreparedStatement ps = connection.prepareStatement(sql);
    Throwable var5 = null;
    try {
      if (params != null) {
        int i = 1;
        Iterator var7 = params.iterator();
        while (var7.hasNext()) {
          Object obj = var7.next();
          ps.setObject(i++, obj);
        } 
      } 
      ResultSet resultSet = ps.executeQuery();
      mapList = convertResultSetToList(resultSet);
      if (logger.isDebugEnabled()) {
        logger.debug("==>  Preparing: {}", sql);
        logger.debug("==> Parameters: {}", params);
        logger.debug("<==      result: {}", mapList.toString());
      } 
    } catch (Throwable var17) {
      var5 = var17;
      throw var17;
    } finally {
      if (ps != null)
        if (var5 != null) {
          try {
            ps.close();
          } catch (Throwable var16) {
            var5.addSuppressed(var16);
          } 
        } else {
          ps.close();
        }  
    } 
    return mapList;
  }
  
  private static List<Map<String, Object>> convertResultSetToList(ResultSet resultSet) throws SQLException {
    List<Map<String, Object>> list = new ArrayList<>();
    ResultSetMetaData md = resultSet.getMetaData();
    int columnCount = md.getColumnCount();
    while (resultSet.next()) {
      Map<String, Object> rowData = new HashMap<>(columnCount);
      for (int i = 1; i <= columnCount; i++) {
        if (resultSet.getObject(i) != null)
          rowData.put(md.getColumnName(i), resultSet.getObject(i)); 
      } 
      list.add(rowData);
    } 
    return list;
  }
}
